package utils

import (
	"github.com/dgrijalva/jwt-go"
	"library/model"
	"time"
)

var jwtKey = []byte("token_key")

type Claims struct {
	UserId uint
	jwt.StandardClaims
}

func ReleaseToken(user model.User)  (string, error){
	expirationTime := time.Now().Add(10*time.Minute)	//10分钟有效期
	claims := &Claims{
		UserId: user.ID,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expirationTime.Unix(),
			IssuedAt: time.Now().Unix(),
			Issuer: "library admin",
			Subject: "user token",
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256,claims)
	tokenString, err := token.SignedString(jwtKey)
	if err != nil {
		return "", err
	}
	return tokenString, nil
}

func ParseToken(tokenString string)  (*jwt.Token, *Claims, error){
	//从tokenString中解析出claims然后返回
	claims := &Claims{}

	token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (i any, err error) {
		return jwtKey, nil
	})

	return token, claims, err
}